package org.jeecg.modules.chg.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.jeecg.modules.chg.entity.ChgArrears;
import org.jeecg.modules.chg.entity.ChgSubArrear;
import org.jeecg.modules.chg.service.IChgArrearsService;
import org.jeecg.modules.chg.service.IChgMpService;
import org.jeecg.modules.chg.service.IChgSubArrearService;
import org.jeecg.modules.chg.vo.ChgArrearsPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 欠费记录
 * @Author: jeecg-boot
 * @Date:   2022-02-13
 * @Version: V1.0
 */
@Api(tags="欠费记录")
@RestController
@RequestMapping("/chg/chgArrears")
@Slf4j
public class ChgArrearsController {
	@Autowired
	private IChgArrearsService chgArrearsService;
	@Autowired
	private IChgSubArrearService chgSubArrearService;
	@Autowired
	private IArcAccountService arcAccountService;
	@Autowired
	private IChgMpService chgMpService;
	@Autowired
	private ISysBaseAPI baseAPI;


	/**
	 * 分页列表查询
	 *
	 * @param chgArrears
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "欠费记录-分页列表查询")
	@ApiOperation(value="欠费记录-分页列表查询", notes="欠费记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ChgArrears chgArrears ,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		chgArrears.setDelFlag(0);
		QueryWrapper<ChgArrears> queryWrapper = QueryGenerator.initQueryWrapper(chgArrears, req.getParameterMap());
		Page<ChgArrears> page = new Page<ChgArrears>(pageNo,pageSize);
		IPage<ChgArrears> pageList = chgArrearsService.page(page, queryWrapper);


//		JSONObject object = new JSONObject();
//		object.put("jwid","gh_f7dc5b9d62ad");
//		JwidModel jwidModel = baseAPI.getJwId(object);
//
//		JSONObject orderObj =new  JSONObject();
//		orderObj.put("package","prepay_id=wx30213401063927349ae9118268edbc0000");
//		Result<?> result = chgMpService.queryMpOrderState(jwidModel, orderObj);
//		System.out.println(result);


		return Result.OK(pageList);
	}


	/**
	 * 收费查询-用户列表
	 *
	 * @param cusVO
	 * @param req
	 * @return
	 */
	@AutoLog(value = "收费查询-用户列表")
	@ApiOperation(value="收费查询-用户列表", notes="收费查询-用户列表")
	@GetMapping(value = "/ufuList")
	public Result<?> ufuList(ArcAccountCusVO cusVO,
								   HttpServletRequest req) {

		List<ArcAccountCusVO> cusVOList=new ArrayList<>();
		if(oConvertUtils.isNotEmpty(cusVO.getId()) || oConvertUtils.isNotEmpty(cusVO.getCode())){
			//缴费账户对应 用户水表信息
			cusVOList = arcAccountService.queryAccount(cusVO.getId(),null,cusVO.getCode());

			//if(null != cusVOList && cusVOList.size()>0){
			//	List<String> cusIds = cusVOList.stream().map(ArcAccountCusVO::getCode).collect(Collectors.toList());
			//	JSONObject rsObj=new JSONObject();
			//	rsObj.put("userInfo",cusVOList);
			//	rsObj.put("userInfo",cusVOList);
			//	return Result.OK(cusVOList);
			//}else {
			//	return Result.error("账户不存在");
			//}
			return Result.OK(cusVOList);
		}
		//ArcAccountCusVO accountCusVO = new ArcAccountCusVO();
		//cusVOList.add(accountCusVO);
		return Result.OK(cusVOList);
	}

	/**
	 * 收费查询
	 *
	 * @param cusVO
	 * @param req
	 * @return
	 */
	@AutoLog(value = "收费查询欠费记录")
	@ApiOperation(value="收费查询欠费记录", notes="收费查询欠费记录")
	@GetMapping(value = "/feesList")
	public Result<?> feesList(ArcAccountCusVO cusVO,
								   HttpServletRequest req) {
		long b= System.currentTimeMillis();
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String tenantIds = sysUser.getRelTenantIds();
		if (oConvertUtils.isNotEmpty(tenantIds)) {
			List<String> tenantIdList = Arrays.asList(tenantIds.split(","));
			TenantContext.setTenant(tenantIdList.get(0));
		}
		String jwid = req.getHeader(CommonConstant.X_JWID);

		List<ChgArrears> arrearsList=new ArrayList<>();
		if(oConvertUtils.isNotEmpty(cusVO.getId()) || oConvertUtils.isNotEmpty(cusVO.getAccCode())){
			//缴费账户对应 用户水表信息
			List<ArcAccountCusVO> cusVOList = arcAccountService.queryAccount(cusVO.getId(),null,cusVO.getAccCode());

			if(null != cusVOList && cusVOList.size()>0){

				Map<String,String>userMap=new HashMap<>();
				for (ArcAccountCusVO cusVO1 : cusVOList) {
					if(!userMap.containsKey(cusVO1.getCusId())){
						userMap.put(cusVO1.getCusId(),cusVO1.getCode());
					}
				}
				List<String> cusIds = cusVOList.stream().map(ArcAccountCusVO::getCode).collect(Collectors.toList());

				LambdaQueryWrapper<ChgArrears> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.in(ChgArrears::getCusId,cusIds);
				queryWrapper.orderByAsc(ChgArrears::getReadMonth);
				queryWrapper.eq(ChgArrears::getDelFlag,0);

				Page<ChgArrears> page = new Page<ChgArrears>(1,100);
				IPage<ChgArrears> pageList = chgArrearsService.page(page, queryWrapper);

				System.out.print("查询欠费时间");
				System.out.print(System.currentTimeMillis()-b);
				BigDecimal arrearMoney =new BigDecimal(0.0);

				if( null != pageList.getRecords()){
					//获取性质id-name
					Map<String,String>natureMap=new HashMap<>();
					List<DictModel> dictItems = baseAPI.getDictItems("mws_t_base_natures,name,id");
					if(null != dictItems && dictItems.size()>0){
						for (DictModel item : dictItems) {
							if(!natureMap.containsKey(item.getValue())){
								natureMap.put(item.getValue(),item.getText());
							}
						}
					}
					for (ChgArrears record : pageList.getRecords()) {
						BigDecimal subtract = record.getArrearMoney().subtract(record.getRecivedMoney());
						arrearMoney = arrearMoney.add(subtract);
					}

					if(oConvertUtils.isNotEmpty(jwid)){
						//动态找出规则表SKU
						pageList.getRecords().forEach(item->{
							item.setNatureName(natureMap.get(item.getNatureId()));
							item.setCusCode(item.getCusId());
							item.setAlienMoney(item.getWuMoney().add(item.getLjMoney().add(item.getPenalty().add(item.getAlienMoney()))));
							item.setArrearMoney(item.getArrearMoney().subtract(item.getRecivedMoney()));
						});
					}else{
						//动态找出规则表SKU
						pageList.getRecords().forEach(item->{
							item.setNatureName(natureMap.get(item.getNatureId()));
							item.setCusCode(item.getCusId());
							item.setArrearMoney(item.getArrearMoney().subtract(item.getRecivedMoney()));
						});

					}

				}

				JSONObject rsObj=new JSONObject();
				rsObj.put("accInfo",cusVOList.get(0));
				rsObj.put("userInfo",cusVOList);
				rsObj.put("feesInfo",pageList.getRecords());
				rsObj.put("arrearMoney",arrearMoney);

				System.out.print("返回时间");
				System.out.print(System.currentTimeMillis()-b);
				return Result.OK(rsObj);
			}else {
				return Result.error("账户不存在");
			}
		}
		//ChgArrears chgArrears = new ChgArrears();
		//chgArrears.setId("0000");
		//arrearsList.add(chgArrears);
		return Result.OK(arrearsList);
	}
	/**
	 * 欠费记录查询
	 *
	 * @param chgArrears
	 * @param req
	 * @return
	 */
	@AutoLog(value = "欠费记录查询")
	@ApiOperation(value="欠费记录查询", notes="欠费记录查询")
	@GetMapping(value = "/queryFeeList")
	public Result<?> queryFeeList(ChgArrears chgArrears,
								   HttpServletRequest req) {
		List<ChgArrears> subArrears=new ArrayList<>();
		if(oConvertUtils.isNotEmpty(chgArrears.getAccCode())){
			List<ArcAccountCusVO> cusVOList = arcAccountService.queryAccount(null,null,chgArrears.getAccCode());
			List<String> cusIds = cusVOList.stream().map(ArcAccountCusVO::getCode).collect(Collectors.toList());

			LambdaQueryWrapper<ChgArrears> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(ChgArrears::getCusId,cusIds);
			queryWrapper.gt(ChgArrears::getPenalty,0);
			queryWrapper.eq(ChgArrears::getDelFlag,0);

			Page<ChgArrears> page = new Page<ChgArrears>(1,100);
			IPage<ChgArrears> pageList = chgArrearsService.page(page, queryWrapper);
			return Result.OK(pageList.getRecords());
		}else {
			return Result.OK(subArrears);
		}
	}
	/**
	 * 欠费明细查询
	 *
	 * @param chgArrears
	 * @param req
	 * @return
	 */
	@AutoLog(value = "欠费明细查询")
	@ApiOperation(value="欠费明细查询", notes="欠费明细查询")
	@GetMapping(value = "/subFeeList")
	public Result<?> subFeeList(ChgArrears chgArrears,
								   HttpServletRequest req) {
		List<ChgSubArrear> subArrears=new ArrayList<>();
		if(oConvertUtils.isNotEmpty(chgArrears.getAccCode())){
			subArrears= chgArrearsService.selectByAccCode(chgArrears.getAccCode());
			return Result.OK(subArrears);
		}else {
			return Result.OK(subArrears);
		}
	}

	/**
	 *   添加
	 *
	 * @param chgArrearsPage
	 * @return
	 */
	@AutoLog(value = "欠费记录-添加")
	@ApiOperation(value="欠费记录-添加", notes="欠费记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ChgArrearsPage chgArrearsPage) {
		ChgArrears chgArrears = new ChgArrears();
		BeanUtils.copyProperties(chgArrearsPage, chgArrears);
//		chgArrearsService.saveMain(chgArrears, chgArrearsPage.getChgSubArrearList());
		return Result.OK("添加成功！");
	}
	 /**
	  *   微信催缴-欠费
	  *
	  * @param chgArrears
	  * @return
	  */
	 @AutoLog(value = "欠费记录-微信欠费催缴")
	 @ApiOperation(value="欠费记录-添加", notes="欠费记录-微信欠费催缴")
	 @GetMapping(value = "/wxmsgArrears")
	 public Result<?> wxmsgArrears(ChgArrears chgArrears ,
							@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							HttpServletRequest req) {
		 return chgArrearsService.wxMsg(chgArrears);
	 }
	 /**
	  *   短信催缴-欠费
	  *
	  * @param chgArrears
	  * @return
	  */
	 @AutoLog(value = "欠费记录-短信催缴")
	 @ApiOperation(value="欠费记录-短信催缴", notes="欠费记录-短信催缴")
	 @GetMapping(value = "/smsmsgArrears")
	 public Result<?> smsmsgArrears(ChgArrears chgArrears ,
							@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							HttpServletRequest req) {
		 return chgArrearsService.smsMsg(chgArrears);
	 }

	 /**
	  *   短信催缴-欠费停水
	  *
	  * @param chgArrears
	  * @return
	  */
	 @AutoLog(value = "欠费记录-短信催缴-欠费停水")
	 @ApiOperation(value="欠费记录-短信催缴-欠费停水", notes="欠费记录-短信催缴-欠费停水")
	 @GetMapping(value = "/smsmsgStopArrears")
	 public Result<?> smsmsgStopArrears(ChgArrears chgArrears ,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 return chgArrearsService.smsStopMsg(chgArrears);
	 }

	/**
	 *  编辑
	 *
	 * @param chgArrearsPage
	 * @return
	 */
	@AutoLog(value = "欠费记录-编辑")
	@ApiOperation(value="欠费记录-编辑", notes="欠费记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ChgArrearsPage chgArrearsPage) {
		ChgArrears chgArrears = new ChgArrears();
		BeanUtils.copyProperties(chgArrearsPage, chgArrears);
		ChgArrears chgArrearsEntity = chgArrearsService.getById(chgArrears.getId());
		if(chgArrearsEntity==null) {
			return Result.error("未找到对应数据");
		}
		chgArrearsService.updateMain(chgArrears, chgArrearsPage.getChgSubArrearList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "欠费记录-通过id删除")
	@ApiOperation(value="欠费记录-通过id删除", notes="欠费记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		chgArrearsService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "欠费记录-批量删除")
	@ApiOperation(value="欠费记录-批量删除", notes="欠费记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.chgArrearsService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "欠费记录-通过id查询")
	@ApiOperation(value="欠费记录-通过id查询", notes="欠费记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ChgArrears chgArrears = chgArrearsService.getById(id);
		if(chgArrears==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(chgArrears);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "欠费明细通过主表ID查询")
	@ApiOperation(value="欠费明细主表ID查询", notes="欠费明细-通主表ID查询")
	@GetMapping(value = "/queryChgSubArrearByMainId")
	public Result<?> queryChgSubArrearListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ChgSubArrear> chgSubArrearList = chgSubArrearService.selectByMainId(id);
		return Result.OK(chgSubArrearList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param chgArrears
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChgArrears chgArrears) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ChgArrears> queryWrapper = QueryGenerator.initQueryWrapper(chgArrears, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ChgArrears> queryList = chgArrearsService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ChgArrears> chgArrearsList = new ArrayList<ChgArrears>();
      if(oConvertUtils.isEmpty(selections)) {
          chgArrearsList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          chgArrearsList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ChgArrearsPage> pageList = new ArrayList<ChgArrearsPage>();
      for (ChgArrears main : chgArrearsList) {
          ChgArrearsPage vo = new ChgArrearsPage();
          BeanUtils.copyProperties(main, vo);
          List<ChgSubArrear> chgSubArrearList = chgSubArrearService.selectByMainId(main.getId());
          vo.setChgSubArrearList(chgSubArrearList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "欠费记录列表");
      mv.addObject(NormalExcelConstants.CLASS, ChgArrearsPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("欠费记录数据", "导出人:"+sysUser.getRealname(), "欠费记录"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ChgArrearsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ChgArrearsPage.class, params);
              for (ChgArrearsPage page : list) {
                  ChgArrears po = new ChgArrears();
                  BeanUtils.copyProperties(page, po);
                  chgArrearsService.saveMain(po, page.getChgSubArrearList(),"1");
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
